package com.fingard.dsp.bank.directbank.glb01;

import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpReceiver;
import com.fingard.net.WebRequest;
import com.fingard.xml.XmlTextWriter;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author Alon on 2019-11-15.
 * @version 1.0
 */
public class GLB01Base extends DirectBase implements ITcpClient {
    private static String charset = "GBK";

    protected void writeCommonHeader(XmlTextWriter xmlWriter, GLB01Header glb01Header) throws Exception {
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
        xmlWriter.writeStartElement("ebank");
        xmlWriter.writeStartElement("head");
        xmlWriter.writeElementString("serviceId", glb01Header.serviceId);
        xmlWriter.writeElementString("customerId", bankFront.loginName);//企业客户号
        xmlWriter.writeElementString("userId", bankFront.org);//企业用户编号
        xmlWriter.writeElementString("reqTime", glb01Header.reqTime);
        xmlWriter.writeElementString("serialNo", glb01Header.serialNo);//唯一请求流水号
        xmlWriter.writeEndElement();//head
    }

    /**
     * 发送银行前置
     *
     * @param p_reqStr
     * @return
     * @throws Exception
     */
    protected String[] sendToBank(String p_reqStr) throws Exception {
        String[] retStr = new String[]{"", ""};
        String tmpUrl = bankFront.serverURL;
        WriteBankLogLn("1.提交银行的地址：" + tmpUrl);
        WriteBankLogStep2(p_reqStr);
        WebRequest tmpWebRequest = new WebRequest(tmpUrl);
        tmpWebRequest.setConnectTimeout(60000);
        tmpWebRequest.setRequestProperty("Method", "POST");
        tmpWebRequest.setRequestProperty("Content-Type", "text/xml; charset=" + getCharset());
        tmpWebRequest.setRequestProperty("connection", "close");//设置连接状态
        byte[] tmpUpBytes = p_reqStr.getBytes(getCharset());
        retStr = tmpWebRequest.upload(tmpUpBytes, getCharset());
        WriteBankLogStep3(retStr[1]);
        return retStr;
    }

    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }

    @Override
    public void getContentLength(TcpReceiver p_receiver) throws Exception {

    }

    /**
     * 直接发送签名HTTP请求
     *
     * @param data 上送报文
     * @return 返回的报文
     */
    public String sendHttpRequestToSign(String data) {
        StringBuffer sb = new StringBuffer("");
        HttpURLConnection connection = null;
        BufferedInputStream in = null;
        BufferedOutputStream o = null;
        try {
            WriteBankLogLn2("Http 签名前报文：" + data);
            connection = (HttpURLConnection) new URL(getHttpUrlToSign()).openConnection();
            connection.setRequestProperty("Content-Type", "INFOSEC_SIGN/1.0");
            String tmp = String.valueOf(data.getBytes(charset).length);
            WriteBankLogLn(getHttpUrlToSign() + "Http 签名报文长度:" + tmp);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Length", tmp);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            o = new BufferedOutputStream(connection.getOutputStream());
            o.write(data.getBytes(charset));
            o.flush();//
            in = new BufferedInputStream(connection.getInputStream());
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                //	System.out.println("Http 上送银行数据为 to sign ： 222222 len = "+len);
                sb.append(new String(buffer, 0, len, charset));
                //	System.out.println("Http 上送银行数据为 to sign ： 222222 sb = "+sb.toString());
            }
        } catch (Exception e) {
            sb = new StringBuffer("-1");
            e.printStackTrace();
            WriteBankLogLn("Http 上送银行数据为 Exception getMessage ：" + e.getMessage());
        } finally {
            if (o != null) {
                try {
                    o.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.disconnect();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        WriteBankLogLn("http通讯银行端返回的交易数据 to sign：" + sb.toString());
        return sb.toString();
    }

    public String getHttpUrlToSign() {
        StringBuffer sb = new StringBuffer("http://" + bankFront.serverIP + ":" + bankFront.signPort);
        return sb.toString();
    }
}
